package com.leo.interview;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *5.（迅雷笔试题）：编写一个程序，开启3个线程，这3个线程的ID分别为A、B、C，每个线程将自己的ID在屏幕上打印10遍，要求输出结果必须按ABC的顺序显示；如：ABCABC….依次递推。
 * @author xuexiaolei
 * @version 2017年11月10日
 */
public class Interview5 {
    private static final int COUNT = 10;
    private static final Object lock = new Object();
    private static volatile String permit = "A";//控制当前执行的线程标识

    public static void main(String[] args) {
        ExecutorService exec = Executors.newFixedThreadPool(3);
        exec.execute(new Task("A"));
        exec.execute(new Task("B"));
        exec.execute(new Task("C"));
        exec.shutdown();
    }

    static class Task implements Runnable {
        private final String name;
        Task(String name) {
            this.name = name;
        }
        @Override public void run() {
            for (int i = 0; i < COUNT; i++) {
                synchronized (lock){
                    while (!this.name.equals(permit)){
                        try {
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.print(this.name);
                    permit = nextPermit(permit);
                    lock.notifyAll();
                }
            }
        }

        private String nextPermit(String permit) {
            if (permit.equals("A")) return "B";
            if (permit.equals("B")) return "C";
            if (permit.equals("C")) return "A";
            throw new RuntimeException("hello");
        }
    }
}
